package edu.chl.dat076.datesite.controllers;

import edu.chl.dat076.datesite.ejbs.ConversationEJBLocal;
import edu.chl.dat076.datesite.ejbs.UserEJBLocal;
import edu.chl.dat076.datesite.entities.Conversation;
import edu.chl.dat076.datesite.entities.Message;
import edu.chl.dat076.datesite.entities.SiteUser;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

/**
 *
 * @author Christoffer
 */
@ManagedBean
@ViewScoped
public class ConversationControllerBean implements Serializable {
    
    @EJB
	private UserEJBLocal userEJBLocal;
	@EJB
	private ConversationEJBLocal conversationEJBLocal;
	
    private SiteUser user = new SiteUser();
	private List<Conversation> conversations;
	
	@PostConstruct
	public void postConstruct() {
		user = userEJBLocal.getUser(FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user").toString());
		conversations = conversationEJBLocal.getAllConversations(user);
	}
	
	public List<Conversation> getConversations() {
		return conversations;
	}
	
	// Hämta den andra användaren i konversationen
	public SiteUser getOtherUser(Conversation conversation) {
		return (conversation.getUser1().equals(user)) ? conversation.getUser2() : conversation.getUser1();
	}
	
	public Message getFirstMessage(Conversation conversation) {
		return (conversation.getMessages().size() > 0) ? conversation.getMessages().get(0) : null;
	}
	
	//  Kolla om det finns några meddelanden som den aktuella användaren inte läst
	public boolean unreadMessages(Conversation conversation) {
		for (Message m : conversation.getMessages()) {
			if (!m.getSender().equals(user))
				if (!m.isRead()) {
					return true;
				}
		}
		return false;
	}
}